import axios from 'axios'

import { message } from 'ant-design-vue'

const http = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 120000
})

// request 拦截器
http.interceptors.request.use(
  config => {
    if (config.method === 'get') {
      config.headers['Cache-Control'] = 'no-cache'
    }
    config.headers['Content-Type'] = 'application/json;charset=ISO8859-1'
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  response => {
    const res = response.data
    if (res.error) {
      message.error(res.error.message)
      if (res.code === '') {
        res.code = '200'
      }
      return Promise.reject(res)
    }
    return Promise.resolve(res)
  },
  error => {
    if (error && error.response) {
      let errorMessage = ''
      switch (error.response.status) {
        case 301:
          errorMessage = '原本存在于该处的资源，已经被永久改变了位置'
          break
        case 304:
          errorMessage = '原本存在于该处的资源，已经被临时改变了位置'
          break
        case 400:
          errorMessage = '错误请求'
          break
        case 401:
          errorMessage = '未登录，授权失败'
          break
        case 403:
          // router.push("/")
          errorMessage = '权限不足导致拒绝访问，请尝试重新登录'
          break
        case 404:
          errorMessage = '未找到该资源'
          break
        case 405:
          errorMessage = '请求方法未允许'
          break
        case 408:
          errorMessage = '请求超时'
          break
        case 500:
          errorMessage = '服务器端出错'
          break
        case 501:
          errorMessage = '网络未实现'
          break
        case 502:
          errorMessage = '网络错误'
          break
        case 503:
          errorMessage = '服务不可用'
          break
        case 504:
          errorMessage = '网络超时'
          break
        case 505:
          errorMessage = 'http版本不支持该请求'
          break
        default:
          errorMessage = `连接错误${error.response.status}`
      }
      message.error(errorMessage, 3)
      return Promise.reject(error)
    }
  }
)

export default http
